package cn.edu.cdtu.healthserver.servlet;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.cdtu.healthserver.domain.Doctor;
import cn.edu.cdtu.healthserver.domain.Register;
import cn.edu.cdtu.healthserver.service.DoctorInformation;
import cn.edu.cdtu.healthserver.service.LoginControl;
import cn.edu.cdtu.healthserver.utils.ConnectUtil;

import com.google.gson.Gson;

/**
 * Servlet implementation class OutputDoctor
 */
@WebServlet("/OutputDoctor")
public class OutputDoctor extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private DoctorInformation doctorInformation = new DoctorInformation();
    private Gson gson = new Gson();

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		OutputStream outputStream = response.getOutputStream();
		String doWhat =  request.getParameter(
				ConnectUtil.HealthDoctorRegister.Option.DO_WHAT); //获得从客户端传入的请求类型    
		if(doWhat.equals(
				ConnectUtil.HealthDoctorRegister.Option.OptionValue.GET_DOCTOR_LIST)){
			response.setContentType(ConnectUtil.ContentTypeString.jSON_STRING);
			List<Doctor> doctors = doctorInformation.outputDoctor();
			outputStream.write(gson.toJson(doctors).getBytes());
		}else if (doWhat.equals(
				ConnectUtil.HealthDoctorRegister.Option.OptionValue.SEND_REG)) {
			Register register = gson.fromJson(request.getParameter(
					ConnectUtil.HealthDoctorRegister.Pargram.REG_GET), Register.class);
			register.setP_id(LoginControl.getLoginedUser(request).getId());
			doctorInformation.insertReg(register);
			outputStream.write(ConnectUtil.HealthDoctorRegister.Result.REG_SUCCESS.getBytes());
		}
		outputStream.flush();
		outputStream.close();
	}

}
